package net.toocruel.iqismart.web.handler;

import net.toocruel.iqismart.entity.rbac.Resource;
import net.toocruel.iqismart.entity.rbac.User;
import net.toocruel.iqismart.entity.setting.Setting;
import net.toocruel.iqismart.entity.setting.SettingWebsite;
import net.toocruel.iqismart.service.ResourceService;
import net.toocruel.iqismart.service.SettingService;
import net.toocruel.iqismart.service.UserService;
import net.toocruel.iqismart.service.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description
 * @Auther sty
 * @createTime 2018/5/2 下午5:07
 */
@Component
public class BaseInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private SettingService settingService;

    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //当前访问路径 用于页面展示菜单
        String requestURI = request.getRequestURI();

        Set<Long> resourceIds = new HashSet<>();

        Resource resource = resourceService.findByLink(requestURI);
        if(resource!=null){
            resourceIds.add(resource.getId());
            resourceIds.add(resource.getParent().getId());
        }

        resource = resourceService.findByLink(requestURI.substring(0,request.getRequestURI().lastIndexOf('/')));
        if(resource!=null){
            resourceIds.add(resource.getId());
            resourceIds.add(resource.getParent().getId());
        }


        request.setAttribute("resourceIds",resourceIds);

        HttpSession session = request.getSession();

        //所有权限 用于页面展示菜单
        if(session.getAttribute("resourceTree") == null){
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            if(auth!=null && auth.getPrincipal() instanceof User){
                User user = (User) auth.getPrincipal();
                session.setAttribute("resourceTree",resourceService.getTree(user.getId()));
            }

        }

        //当前登录用户
        if(session.getAttribute("currentUser") == null){
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            if(auth!=null && auth.getPrincipal() instanceof User){
                User user = (User) auth.getPrincipal();
                //当前用户信息 放到session
                session.setAttribute("currentUser",userService.getById(user.getId()));
            }

        }

        String url=request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+'/';
        if(StringUtils.isBlank(Setting.SETTING.getWebsite().getUrl()) ||
                !StringUtils.equals(Setting.SETTING.getWebsite().getUrl(),url)){
            SettingWebsite website = settingService.getSetting().getWebsite();
            website.setUrl(url);
            settingService.update(website);

        }



        return true;// 只有返回true才会继续向下执行，返回false取消当前请求
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(request.getAttribute("error")!=null){
        }else{
            BusinessException error = new BusinessException("","");
            request.setAttribute("error",error);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


}
